package com.kehutong.charge.service.impl;

import com.kehutong.charge.entity.PayBillRecords;
import com.kehutong.charge.entity.ReceiptManages;
import com.kehutong.charge.entity.ReceiptOrders;
import com.kehutong.charge.service.PayManagesService;
import com.kehutong.charge.service.ReceiptManagesService;
import com.kehutong.charge.service.ReceiptOrdersService;
import com.kehutong.charge.util.PdfUtil;
import com.kehutong.charge.vo.BillInfoListVO;
import com.kehutong.common.DeptService;
import com.kehutong.common.dto.DeptDTO;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.Token;
import org.coraframework.converter.util.StringUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: kht
 * @description: ReceiptManagesServiceImpl
 * @author: jian Ye
 * @create: 2021/8/3
 **/
public class ReceiptManagesServiceImpl implements ReceiptManagesService {

    private static final Logger logger = LoggerFactory.getLogger(ReceiptManagesServiceImpl.class);


    @Inject
    private JdbcSession jdbcSession;
    @Inject
    FileUrlConfig fileUrlConfig;
    @Inject
    DeptService deptService;
    @Inject
    ReceiptOrdersService receiptOrderService;
    @Inject
    PayManagesService payManagesService;


    @Override
    public Page<ReceiptManages> findPage(JSONObject jsonObject) {
        FindPage<ReceiptManages> find = jdbcSession.findPage(ReceiptManages.class)
                .eq("deleted", false)
                .eq(jsonObject,"status")
                .like(jsonObject,"receiptName")
                .like(jsonObject,"communityList")
                .order("createTime", "desc");

        return find.page(jsonObject).exe();
    }


    @Override
    public List<ReceiptManages> findList(JSONObject jsonObject) {
        List<ReceiptManages> receiptList = jdbcSession.findArray(ReceiptManages.class)
                .eq("deleted", false)
                .like(jsonObject,"communityList")
                .exe();

        return receiptList;
    }


    @Override
    public Object save(ReceiptManages receiptManages) throws Exception {
        return null;
    }

    @Override
    public Object save(ReceiptManages entity, Token token) {
        JSONObject jsonO = new JSONObject();
        //查询小区是否已存在模板
        List<String> communityList = entity.getCommunityList();
        if(StringUtil.isEmpty(entity.getSealImgId()) || Objects.isEmpty(communityList)){
            return Result.error(0, "有必填项目没有填，请先检查！");
        }

        for (int i = 0; i < communityList.size() ; i++) {
            jsonO.put("communityList",communityList.get(i));
            List<ReceiptManages> listObj = findList(jsonO);
            if(!Objects.isEmpty(listObj)){
                return Result.error(0, "该小区模板已经存在，请先检查！");
            }
        }
        FileOutputStream outputFileStream = null;
        try {
            //上传的签章图片
            String fileImg = fileUrlConfig.getFile(entity.getSealImgId());
            //使用自定义模板内容
            //ReceiptTemplate receiptTemplate = receiptTempService.findById("162227466631692466");
            PdfUtil pdfUtil = new PdfUtil();
            //保持时生成PDF文件保存到文件服务器
            byte[] pdf = pdfUtil.execute(pdfUtil.dataGenera(fileImg,entity.getReceiptName(),"receipt",""));
            String pdfName = System.currentTimeMillis()+".pdf";
            File file = new File(pdfName);
            outputFileStream = new FileOutputStream(file);
            outputFileStream.write(pdf);
            outputFileStream.close();
            JSONObject jsonObject =  fileUrlConfig.sendFile(file, http->{ });
            entity.setFileId(jsonObject.getJSONObject("data").getString("id"));
            List<String> departList = token.getDepartments();
            if(null == departList || departList.size() == 0){
                logger.error("用户{}数据异常，部门为空！",token.getUsername());
                return Result.error(0, "用户数据异常,生成票据失败！");
            }

            DeptDTO deptDTO = deptService.getDept(departList.get(0));
            entity.setDepartmentNo(deptDTO.getDepartmentNo());
            entity.setDepartmentNos(deptDTO.getDepartmentNos());
            entity.setDepartmentName(deptDTO.getDepartmentName());
            entity.setCreateName(token.getUsername());

            //文件上传成功后自动删除
            if (file.exists() && file.isFile() && file.delete() == true) {
                logger.info("{}本地文件已经删除!",pdfName);
            }
            return jdbcSession.insert(entity);
        } catch (Exception e) {
            logger.error("用户{}生成PDF失败！",token.getUsername(),e);
            return Result.error(0, "生成收据失败！");
        } finally {
            if(outputFileStream != null){
                try {
                    outputFileStream.close();
                } catch (IOException e) {
                    logger.error("用户{}生成PDF ,IOException！",token.getUsername(),e);
                }
            }
        }
    }


    @Override
    public Object findReceiptAndInvoice(JSONObject jsonObject) {
        String houseNo = jsonObject.getString("houseBillNo");
        if(StringUtil.isEmpty(houseNo)){
            return com.kehutong.common.errcode.Result.error(0,"获取票据列表失败！房屋账单编号不能为空");
        }
        List<ReceiptOrders> receiptList = receiptOrderService.findListByHouseNo(houseNo);
        List<PayBillRecords> bIllRecordListByHouseNo = payManagesService.findBIllRecordListByHouseNo(houseNo);
        List<BillInfoListVO> result = new ArrayList();

        BillInfoListVO vo;
        for (ReceiptOrders receipt : receiptList) {
            vo = new BillInfoListVO();
            vo.setTypeName("收据");
            vo.setState(receipt.getEnableStat().getId().equals("0")?"已生成":"已失效");
            vo.setFileId(receipt.getFileId());
            vo.setInfoNo(receipt.getReceiptNo());
            vo.setCreateTime(receipt.getCreateTime());
            result.add(vo);
        }
        for (PayBillRecords records : bIllRecordListByHouseNo) {
            vo = new BillInfoListVO();
            vo.setTypeName("缴费单");
            vo.setState(records.getEnableStat().getId().equals("0")?"已生成":"已失效");
            vo.setFileId(records.getFileId());
            vo.setInfoNo(records.getPayBillNo());
            vo.setCreateTime(records.getCreateTime());
            result.add(vo);
        }
        result = result.stream().sorted(Comparator.comparing(BillInfoListVO::getCreateTime).reversed()).collect(Collectors.toList());
        return result;
    }


    @Override
    public Object update(ReceiptManages receiptManages) throws Exception {
        return jdbcSession.updateById(receiptManages);
    }

    @Override
    public Object deleteById(String id) {
        ReceiptManages result = Pool.get(ReceiptManages.class, id);
        if (result != null) {
            result.setDeleted(true);
            jdbcSession.updateById(result);
        }
        return 1;
    }


}
